package flowlight.action;

import flowlight.utils.JsonVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;


@Controller
@RequestMapping("flowlight")

public class FilwUploadAction {

    @ResponseBody
    @RequestMapping(value = "uploadPic",method = RequestMethod.POST)
    public JsonVo<String> upload( @RequestParam(value = "file")MultipartFile file,HttpServletRequest request) throws Exception {
        JsonVo<String> jsonVo = new JsonVo<String>();
        String projectServerPath = request.getScheme() + "://"+request.getServerName()+":" +
                request.getServerPort() + request.getContextPath() + "/upload/";
        //如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
            //上传文件路径
            String path = request.getServletContext().getRealPath("/images/");
            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));
            jsonVo.setCode(200);
            jsonVo.setMsg("图片上传成功");
            jsonVo.setData(projectServerPath + filename);
            return jsonVo;
        } else {
            jsonVo.setCode(201);
            return jsonVo;
        }

    }
}
